<?php

/**
 * @Description    
 * @Author         zhaojiping
 * @Copyright      山东艾思软件科技有限公司(https://www.aisisofit.cn)
 * @Date           2022-6-15
 * @CreateBy       vs code
 */

namespace app\base\model;

use app\base\validate\BaseLog as ValidateBaseLog;
use app\common\model\CommonModel;
use think\facade\Db;

class BaseLog extends CommonModel {
    protected $order = 'id desc';
    protected $fields = 'id, user_id, url, title, content, ip, create_time, row_id, table_name';

    public function setContentAttr($val) {
        return json_encode($val);
    }

    public function getContentAttr($val) {
        return json_decode($val);
    }

    /**
     * @param Array $fields 需要录入日志的字段 可以是一维或二维 eg:  $fields = ['手机号' => 'mobile'] eg: $fields = ['会员等级' => ['CmsVipLevel', 'vip_level_id', 'name', 'id'] ], // 表名、字段、查询字段、映射字段
     * @param Array $row    修改的数据
     * @param Array $oldRow 修改之前的数据
     * @param String $tableName 修改数据所在表名称
     */
    public static function writeJson($fields, $row, $oldRow, $tableName) {
        $logs = [];
        foreach ($fields as $key => $val) {
            if (is_array($val)) { // ID转明文
                if (isset($row[$val[1]]) && $row[$val[1]] != $oldRow[$val[1]]) {
                    $newName = Db::name($val[0])->where($val[3], $row[$val[1]])->value($val[2]);
                    $oldName = Db::name($val[0])->where($val[3], $oldRow[$val[1]])->value($val[2]);
                    $logs[] = ["{$key}修改", [
                        'column' => $val,
                        'remarks' => ['old' => $oldName, 'new' => $newName],
                        'value' => ['old' => $oldRow[$val[1]], 'new' => $row[$val[1]]]
                    ], $tableName, $row['id']];
                }
            } elseif (isset($row[$val]) && $row[$val] != $oldRow[$val]) {
                $logs[] = ["{$key}修改", [
                    'column' => $val,
                    'remarks' => ['old' => $oldRow[$val], 'new' => $row[$val]],
                    'value' => ['old' => $oldRow[$val], 'new' => $row[$val]]
                ], $tableName, $row['id']];
            }
        }
        self::writeAll($logs);
    }

    /**
     * @param String $title 记录标题
     * @param mixed $content 记录内容
     * @param String $table_name 修改记录所在表明
     * @param Int $row_id 修改记录ID
     */
    public static function write($title, $content, $table_name, $row_id) {
        $model = app('http')->getName();
        $controller = request()->controller();
        $action = request()->action();
        $url = $model . '/' . $controller . '/' . $action;
        $ip = request()->ip();
        $user_id =  defined('UID') ? constant('UID') : 0;
        $log = compact('url', 'user_id', 'ip', 'title', 'content', 'table_name', 'row_id');
        $validate = new ValidateBaseLog();
        if (!$validate->check($log)) {
            return $validate->getError();
        }
        $model = new BaseLog();
        $res = $model->save($log);
        return $res;
    }

    /**
     * 保存多条记录
     * @param Array $data eg:[['记录标题1', '记录内容1', '修改记录所在表明1', '修改记录ID1'],['记录标题2', '记录内容2', '修改记录所在表明2', '修改记录ID2']]
     */
    public static function writeAll($data = []) {
        $kes = ['title', 'content', 'table_name', 'row_id'];
        $logs = [];
        foreach ($data as $log) {
            if (count($kes) != count($log)) {
                return false;
            }
            $log = array_combine($kes, $log);
            $model = app('http')->getName();
            $controller = request()->controller();
            $action = request()->action();
            $log['url'] = $model . '/' . $controller . '/' . $action;
            $log['ip'] = request()->ip();
            $log['user_id'] =  defined('UID') ? constant('UID') : 0;
            $validate = new ValidateBaseLog();
            if (!$validate->check($log)) {
                return $validate->getError();
            }
            $logs[] = $log;
        }
        $model = new BaseLog();
        $res = $model->saveAll($logs);
        return $res;
    }
}
